var gulp = require('gulp');
var proxy = require('proxy-middleware');
var browserSync = require('browser-sync');
var $ = require('gulp-load-plugins')();
var reload = browserSync.reload;
var url = require('url');
var postcss = require('gulp-postcss');
var pxtorem = require('postcss-pxtorem');
var autoprefixer = require('gulp-autoprefixer');

var options_rem = [
  pxtorem({
    rootValue: 50, // 定义根节点
    unitPrecision: 5, // 允许rem的小数位数
    propList: ['*'], // 允许转化的属性
    selectorBlackList: [],
    replace: true, // 是否替换调原来的属性
    mediaQuery: false, //
    minPixelValue: 5 // 转化的最小px
  })
];

gulp.task('template', function() {
  return gulp.src('app/*/**/*.html')
    .pipe($.htmlmin({ collapseWhitespace: true, removeComments: true, minifyCSS: true }))
    .pipe($.angularTemplatecache({ module: 'app' }))
    .pipe($.uglify())
    .pipe(gulp.dest('.tmp'));
});

gulp.task('images', function() {
  return gulp.src('app/img/**/*')
    .pipe($.imagemin({
      progressive: true,
      interlaced: true
    }))
    .pipe(gulp.dest('dist/img'));
});

gulp.task('copy', function() {
  return gulp.src('app/static/*')
    .pipe(gulp.dest('dist/static'));
});

gulp.task('build', ['template', 'images', 'copy'], function() {
  return gulp.src(['app/*.html'])
    .pipe($.inject(gulp.src('.tmp/templates.js'), {
      starttag: '<!-- inject:partials -->',
      relative: true
    }))
    .pipe($.useref())
    .pipe($.if('*.html', $.htmlmin({ collapseWhitespace: true, removeComments: true, minifyCSS: true })))
    .pipe($.if('*.js', $.ngAnnotate()))
    .pipe($.if('*.js', $.uglify()))
    .pipe($.if('*.css',autoprefixer({
      browsers: ['last 8 versions'],
      cascade: false
    })))
    .pipe($.if('*.css', $.cleanCss()))
    .pipe(gulp.dest('dist'));
});

gulp.task('serve', function() {
  var proxyOptions = url.parse('http://policy.51tongcai.com/client/api');
  proxyOptions.route = '/api';
  var proxyOptions1 = url.parse('http://option.51tongcai.com/client/quoteapi');
  proxyOptions1.route = '/quoteapi';
  var proxyOptions2 = url.parse('http://policy.51tongcai.com/client/eamapi');
  proxyOptions2.route = '/eamapi';
  browserSync({
    notify: false,
    port: 9002,
    server: {
      baseDir: ['app'],
      middleware: [proxy(proxyOptions), proxy(proxyOptions1), proxy(proxyOptions2)],
      index: 'index.html',
      directory: true,
      routes: {
        '/node_modules': 'node_modules',
        '/public/img': 'app/img',
        '/source/img': 'app/img'
      }
    }
  });

  gulp.watch([
    'app/*',
    'app/**/*',
    'app/**/**/*',
  ]).on('change', function(event) {
    if (event.type === 'added' || event.type === 'deleted') { // 如果是添加删除js或css。重新注入
      gulp.src('app/index.html')
        .pipe($.inject(gulp.src([
          'app/public/index.js',
          'app/public/modules/*.js',
          'app/public/config/*.js',
          'app/public/config.js',
          'app/public/run.js',
          'app/public/route.js',
          'app/public/tools.js',
          'app/public/css/*.css',
          'app/public/serve/*.js',
          'app/public/directive/*',
          'app/source/**/*',
        ]), { relative: true }))
        .pipe(gulp.dest('app'))
        .on('end', reload);
    } else {
      var changePath = event.path.substring(event.path.indexOf('app'));
      if (event.path.substr(-3, 3) === 'css') { // 如果修改的文件是css，对该文件进行rem转化
        gulp.src(changePath, { base: 'app' })
          .pipe(gulp.dest('app'))
          .on('end', reload);
      } else {
        reload();
      }
    }
  });

});

gulp.task('dist-serve', function() {
  var proxyOptions = url.parse('http://172.0.3.45:12000');
  proxyOptions.route = '/api';
  var proxyOptions1 = url.parse('http://114.215.238.135:8080/static/');
  proxyOptions1.route = '/static';
  var proxyOptions2 = url.parse('http://114.215.238.135:8080/client/000003');
  proxyOptions2.route = '/api/000003';
  var proxyOptions3 = url.parse('http://trade.360lhy.com/quoteapi/');
  proxyOptions3.route = '/quoteapi';
  browserSync({
    notify: false,
    port: 9001,
    server: {
      baseDir: ['dist'],
      middleware: [proxy(proxyOptions), proxy(proxyOptions1), proxy(proxyOptions2), proxy(proxyOptions3)],
      index: 'index.html',
    }
  });
});

gulp.task('default', ['serve']);
